using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoUpdater
{
    public class UpgradeManager
    {
        // 配置与状态字段
        private readonly string _currentVersion;
        private readonly string _localConfigPath;
        private LocalUpgradeConfig _localConfig;
        private ServerUpgradeConfig _serverConfig;
        private readonly DownloadManager _downloadManager;
        private int _downloadRetryCount;
        private const int MaxRetryCount = 5;
        private const int RetryIntervalMinutes = 5;
        private int _installationProgress = 0;

        // 事件定义
        public event Action<UpgradeStatus> StatusChanged;
        public event Action<int> DownloadProgressChanged;
        public event Action<int> InstallProgressChanged;
        public event Action<string> StatusMessageUpdated;

        // 新增：服务器连接相关常量
        private const int MaxConnectionRetries = 5; // 最大连接重试次数
        private int _connectionRetryCount = 0;      // 当前重试次数

        // 新增：服务器连接成功事件
        public event Action ServerConnected;

        // 新增：本地版本号存储
        private string _localVersionFromRegistry;
        private string _localVersionFromFile;

        // 属性
        public UpgradeStatus CurrentStatus { get; private set; }
        public string DownloadFilePath { get; private set; }

        // Windows内核函数（强制删除）
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
        private const uint MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004;

        public UpgradeManager(string currentVersion)
        {
            CompatibilityHelper.ConfigureSecurityProtocols();

            _currentVersion = currentVersion;
            _localConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "LocalUpgrade.ini");

            EnsureConfigDirectoryExists();
            _downloadManager = new DownloadManager();

            // 注册下载事件
            _downloadManager.ProgressChanged += OnDownloadProgressChanged;
            _downloadManager.DownloadCompleted += OnDownloadCompleted;

            ChangeStatus(UpgradeStatus.Starting);
        }

        private void EnsureConfigDirectoryExists()
        {
            string configDir = Path.GetDirectoryName(_localConfigPath);
            if (!Directory.Exists(configDir)) Directory.CreateDirectory(configDir);
            if (!File.Exists(_localConfigPath)) CreateDefaultLocalConfig();
        }

        private void CreateDefaultLocalConfig()
        {
            try
            {
                var iniFile = new IniFile(_localConfigPath);
                iniFile.Write("UpgradeSettings", "UpgradeServerUrl", "");
                iniFile.Write("UpgradeSettings", "LastUpgradeTime", DateTime.MinValue.ToString());
                iniFile.Write("UpgradeSettings", "LastUpgradeFileName", "");
                iniFile.Write("UpgradeSettings", "LastUpgradeFileUrl", "");
                iniFile.Write("UpgradeSettings", "UpgradeStatus", UpgradeStatus.Starting.ToString());
                iniFile.Write("UpgradeSettings", "UpgradePostpone", "0");
            }
            catch (Exception ex) { Logger.Error($"创建默认配置失败: {ex.Message}"); }
        }

        public async Task StartUpgradeProcess()
        {
            try
            {
                if (!CompatibilityHelper.EnsureAdminRights())
                {
                    UpdateStatusMessage("需要管理员权限才能继续");
                    ChangeStatus(UpgradeStatus.PreUpgradeFailed);
                    return;
                }

                await Task.Run(() => LoadLocalConfig());

                bool connectionSuccess = await RetryServerConnection();
                if (!connectionSuccess)
                {
                    ChangeStatus(UpgradeStatus.ServerConnectionFailed);
                    return;
                }

                ServerConnected?.Invoke();

                bool versionCheckSuccess = await CheckVersion();
                if (!versionCheckSuccess)
                {
                    ChangeStatus(UpgradeStatus.PreUpgradeVersionFailed);
                    return;
                }

                // 版本不同时自动开始升级，无需手动点击
                if (!IsVersionEqualOrNewer())
                {
                    await StartDownload(); // 自动开始下载
                }
                else
                {
                    ChangeStatus(UpgradeStatus.PreUpgradeVersionEqual);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                ChangeStatus(UpgradeStatus.PreUpgradeFailed);
            }
        }
        /// <summary>
        /// 带重试机制的服务器连接
        /// </summary>
        private async Task<bool> RetryServerConnection()
        {
            _connectionRetryCount = 0;

            while (_connectionRetryCount < MaxConnectionRetries)
            {
                try
                {
                    UpdateStatusMessage($"连接服务器（{_connectionRetryCount + 1}/{MaxConnectionRetries}）...");
                    bool success = await GetServerUpgradeConfig();

                    if (success)
                    {
                        UpdateStatusMessage("服务器连接成功");
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warn($"第{_connectionRetryCount + 1}次连接失败: {ex.Message}");
                }

                _connectionRetryCount++;

                // 重试前等待（指数退避策略：1s, 2s, 4s, 8s, 16s）
                int delaySeconds = (int)Math.Pow(2, _connectionRetryCount);
                UpdateStatusMessage($"连接失败，{delaySeconds}秒后重试...");
                await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
            }

            // 达到最大重试次数
            Logger.Error($"已达到最大重试次数（{MaxConnectionRetries}次），连接服务器失败");
            return false;
        }


        private void LoadLocalConfig()
        {
            try
            {
                UpdateStatusMessage("加载本地配置...");
                var iniFile = new IniFile(_localConfigPath);

                _localConfig = new LocalUpgradeConfig
                {
                    UpgradeServerUrl = iniFile.Read("UpgradeSettings", "UpgradeServerUrl"),
                    LastUpgradeFileName = iniFile.Read("UpgradeSettings", "LastUpgradeFileName"),
                    LastUpgradeFileUrl = iniFile.Read("UpgradeSettings", "LastUpgradeFileUrl"),
                    UpgradeStatus = iniFile.Read("UpgradeSettings", "UpgradeStatus"),
                    UpgradePostpone = int.TryParse(iniFile.Read("UpgradeSettings", "UpgradePostpone"), out int p) ? p : 0
                };

                if (!DateTime.TryParse(iniFile.Read("UpgradeSettings", "LastUpgradeTime"), out var lastTime))
                    _localConfig.LastUpgradeTime = DateTime.MinValue;
            }
            catch (Exception ex) { Logger.Error($"加载配置失败: {ex.Message}"); throw; }
        }

        private void SaveLocalConfig()
        {
            try
            {
                var iniFile = new IniFile(_localConfigPath);
                iniFile.Write("UpgradeSettings", "UpgradeServerUrl", _localConfig.UpgradeServerUrl);
                iniFile.Write("UpgradeSettings", "LastUpgradeTime", DateTime.Now.ToString());
                iniFile.Write("UpgradeSettings", "LastUpgradeFileName", _localConfig.LastUpgradeFileName);
                iniFile.Write("UpgradeSettings", "LastUpgradeFileUrl", _localConfig.LastUpgradeFileUrl);
                iniFile.Write("UpgradeSettings", "UpgradeStatus", CurrentStatus.ToString());
                iniFile.Write("UpgradeSettings", "UpgradePostpone", _localConfig.UpgradePostpone.ToString());
            }
            catch (Exception ex) { Logger.Error($"保存配置失败: {ex.Message}"); }
        }

        private async Task<bool> GetServerUpgradeConfig()
        {
            try
            {
                UpdateStatusMessage("获取服务器配置...");
                if (string.IsNullOrEmpty(_localConfig.UpgradeServerUrl)) { Logger.Error("服务器地址未配置"); return false; }

                string serverUrl = _localConfig.UpgradeServerUrl.TrimEnd('/');
                string configUrl = $"{serverUrl}/Upgrade.ini";
                using (var client = new TimeoutWebClient(30000))
                {
                    client.Headers.Add("User-Agent", "AutoUpdater/1.0");
                    string configContent = await client.DownloadStringTaskAsync(configUrl);

                    // 验证配置内容是否有效
                    if (string.IsNullOrWhiteSpace(configContent))
                    {
                        Logger.Error("获取到的upgrade.ini内容为空");
                        return false;
                    }
                    return ParseServerConfig(configContent);
                }
            }
            catch (WebException ex)
            {
                Logger.Error($"获取配置失败: {ex.Message}");

                // 细化日志：明确记录404等无法找到文件的错误
                if (ex.Response is HttpWebResponse resp)
                {
                    Logger.Error($"获取upgrade.ini失败，HTTP状态码: {resp.StatusCode} " + $"(可能原因：文件不存在或路径错误)");
                }
                else
                {
                    Logger.Error($"获取upgrade.ini失败: {ex.Message}");
                }
                return false;
            }
            catch (Exception ex) { Logger.Error($"获取配置失败: {ex.Message}"); return false; }
        }

        private bool ParseServerConfig(string configContent)
        {
            try
            {
                string tempPath = Path.Combine(Path.GetTempPath(), "Upgrade.ini");
                File.WriteAllText(tempPath, configContent);
                var iniFile = new IniFile(tempPath);

                _serverConfig = new ServerUpgradeConfig
                {
                    UpgradeFileVersion = iniFile.Read("Upgrade", "UpgradeFileVersion"),
                    UpgradeFileName = iniFile.Read("Upgrade", "UpgradeFileName"),
                    UpgradeFileUrl = iniFile.Read("Upgrade", "UpgradeFileUrl"),
                    UpgradeFileMD5 = iniFile.Read("Upgrade", "UpgradeFileMD5"),
                    UpgradeFileDescription = iniFile.Read("Upgrade", "UpgradeFileDescription"),
                    ForceUpgrade = bool.TryParse(iniFile.Read("Setting", "ForceUpgrade"), out var f) && f,
                    ForceSystemRestart = bool.TryParse(iniFile.Read("Setting", "ForceSystemRestart"), out var r) && r
                };

                if (string.IsNullOrEmpty(_serverConfig.UpgradeFileVersion) ||
                    string.IsNullOrEmpty(_serverConfig.UpgradeFileUrl))
                    return false;

                return true;
            }
            catch (Exception ex) { Logger.Error($"解析配置失败: {ex.Message}"); return false; }
        }

        private Task<bool> CheckVersion()
        {
            return Task.Run(() =>
            {
                try
                {
                    UpdateStatusMessage("检查版本信息...");
                    // 1. 验证服务器版本配置
                    if (_serverConfig == null || string.IsNullOrEmpty(_serverConfig.UpgradeFileVersion))
                    {
                        Logger.Error("服务器版本配置无效");
                        return false;
                    }

                    // 2. 从注册表获取版本号
                    _localVersionFromRegistry = GetVersionFromRegistry();

                    // 3. 从指定文件获取版本号
                    _localVersionFromFile = GetVersionFromFile();

                    // 4. 输出获取到的版本信息（用于调试和日志）
                    Logger.Info($"从注册表获取版本: {(_localVersionFromRegistry ?? "未找到")}");
                    Logger.Info($"从文件获取版本: {(_localVersionFromFile ?? "未找到")}");
                    Logger.Info($"服务器版本: {_serverConfig.UpgradeFileVersion}");

                    // 5. 验证至少有一种方式获取到本地版本
                    if (string.IsNullOrEmpty(_localVersionFromRegistry) &&
                        string.IsNullOrEmpty(_localVersionFromFile))
                    {
                        Logger.Error("无法从注册表或文件获取本地版本号");
                        UpdateStatusMessage("获取本地版本失败");
                        //return false;  //del by sun
                    }
                    return true;
                }
                catch (Exception ex) { Logger.Error($"版本检查失败: {ex.Message}"); return false; }
            });
        }

        //public bool IsVersionEqualOrNewer()
        //{
        //    try
        //    {
        //        string cleanCurrent = _currentVersion.StartsWith("V", StringComparison.OrdinalIgnoreCase)
        //            ? _currentVersion.Substring(1) : _currentVersion;
        //        string cleanServer = _serverConfig.GetCleanVersion();

        //        return new Version(cleanCurrent) >= new Version(cleanServer);
        //    }
        //    catch (Exception ex) { Logger.Error($"版本比较失败: {ex.Message}"); return false; }
        //}

        /// <summary>
        /// 从注册表获取版本号
        /// 路径：HKLM\SOFTWARE\BlueEngine-Agent\Version
        /// </summary>
        private string GetVersionFromRegistry()
        {
            try
            {
                // 访问HKLM需要管理员权限，32位程序在64位系统需指定RegistryView
                using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                                                           Environment.Is64BitOperatingSystem ?
                                                           RegistryView.Registry64 : RegistryView.Registry32))
                {
                    using (var subKey = baseKey.OpenSubKey("SOFTWARE\\BlueEngine-Agent"))
                    {
                        if (subKey == null)
                        {
                            Logger.Warn("注册表项HKLM\\SOFTWARE\\BlueEngine-Agent不存在");
                            return null;
                        }

                        var versionValue = subKey.GetValue("Version")?.ToString();
                        return string.IsNullOrWhiteSpace(versionValue) ? null : versionValue.Trim();
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                Logger.Warn($"没有权限访问注册表: {ex.Message}");
                return null;
            }
            catch (Exception ex)
            {
                Logger.Error($"读取注册表版本失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 从指定文件获取版本号
        /// 路径：C:\Program File (x86)\BlueEngine-Agent\version.txt
        /// </summary>
        private string GetVersionFromFile()
        {
            try
            {
                var filePath = Path.Combine(
                                    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                                    "BlueEngine-Agent",
                                    "version.txt"
                                );

                if (!File.Exists(filePath))
                {
                    Logger.Warn($"版本文件不存在: {filePath}");
                    return null;
                }

                // 读取文件内容（支持UTF-8和ANSI编码）
                var content = File.ReadAllText(filePath).Trim();
                return string.IsNullOrWhiteSpace(content) ? null : content;
            }
            catch (UnauthorizedAccessException ex)
            {
                Logger.Warn($"没有权限读取版本文件: {ex.Message}");
                return null;
            }
            catch (Exception ex)
            {
                Logger.Error($"读取版本文件失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 判断版本是否最新（使用获取到的本地版本）
        /// </summary>
        public bool IsVersionEqualOrNewer()
        {
            try
            {
                // 优先使用注册表版本，注册表不存在则使用文件版本
                string localVersion = !string.IsNullOrEmpty(_localVersionFromRegistry)
                    ? _localVersionFromRegistry
                    : _localVersionFromFile;

                if (string.IsNullOrEmpty(localVersion))
                {
                    Logger.Error("没有可用的本地版本号进行比较");
                    return false;
                }

                string cleanCurrent = localVersion.StartsWith("V", StringComparison.OrdinalIgnoreCase)
                    ? localVersion.Substring(1)
                    : localVersion;
                string cleanServer = _serverConfig.GetCleanVersion();

                return new Version(cleanCurrent) >= new Version(cleanServer);
            }
            catch (Exception ex)
            {
                Logger.Error($"版本比较失败: {ex.Message}");
                return false;
            }
        }

        public Task StartDownload()
        {
            return Task.Run(() =>
            {
                try
                {
                    if (string.IsNullOrEmpty(_serverConfig.UpgradeFileUrl))
                    {
                        Logger.Error("下载地址为空");
                        ChangeStatus(UpgradeStatus.DownloadFailed);
                        return;
                    }

                    _localConfig.LastUpgradeFileUrl = _serverConfig.UpgradeFileUrl;
                    _localConfig.LastUpgradeFileName = _serverConfig.UpgradeFileName;
                    SaveLocalConfig();

                    string fileName = _serverConfig.UpgradeFileName.Trim();
                    string downloadDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Updates");
                    if (!Directory.Exists(downloadDir)) Directory.CreateDirectory(downloadDir);
                    DownloadFilePath = Path.GetFullPath(Path.Combine(downloadDir, fileName));

                    UpdateStatusMessage("开始下载升级文件...");
                    ChangeStatus(UpgradeStatus.Downloading);
                    _downloadManager.StartDownload(_serverConfig.UpgradeFileUrl, DownloadFilePath);
                }
                catch (Exception ex) { Logger.Error($"下载准备失败: {ex.Message}"); ChangeStatus(UpgradeStatus.DownloadFailed); }
            });
        }

        private void OnDownloadProgressChanged(object sender, DownloadProgressEventArgs e)
        {
            DownloadProgressChanged?.Invoke(e.ProgressPercentage);
            UpdateStatusMessage($"正在下载: {e.ProgressPercentage}% ({FormatFileSize(e.BytesReceived)}/{FormatFileSize(e.TotalBytesToReceive)})");
        }

        private string FormatFileSize(long bytes)
        {
            return bytes < 1024 ? $"{bytes} B" :
                   bytes < 1048576 ? $"{(bytes / 1024.0):F1} KB" :
                   bytes < 1073741824 ? $"{(bytes / 1048576.0):F1} MB" :
                   $"{(bytes / 1073741824.0):F1} GB";
        }

        private async void OnDownloadCompleted(object sender, DownloadCompletedEventArgs e)
        {
            if (e.Success)
            {
                UpdateStatusMessage("校验文件完整性...");
                bool fileValid = await VerifyFileExistenceAndAccess(e.LocalFilePath);
                if (!fileValid) { await HandleDownloadRetry(); return; }

                bool md5Valid = FileChecker.VerifyMD5WithDetail(e.LocalFilePath, _serverConfig.UpgradeFileMD5);
                if (md5Valid)
                {
                    _localConfig.LastUpgradeFileName = Path.GetFileName(e.LocalFilePath);
                    SaveLocalConfig();
                    ChangeStatus(UpgradeStatus.DownloadSuccess);
                    await StartInstallation();
                }
                else
                {
                    await HandleDownloadRetry();
                }
            }
            else
            {
                await HandleDownloadRetry();
            }
        }

        private async Task<bool> VerifyFileExistenceAndAccess(string filePath)
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    if (!File.Exists(filePath)) { await Task.Delay(200); continue; }
                    using (var stream = File.OpenRead(filePath))
                    {
                        if (stream.Length == 0) { await Task.Delay(200); continue; }
                        return true;
                    }
                }
                catch { await Task.Delay(200); }
            }
            return false;
        }

        private async Task HandleDownloadRetry()
        {
            _downloadRetryCount++;
            if (_downloadRetryCount < MaxRetryCount)
            {
                ChangeStatus(UpgradeStatus.DownloadRetry);
                UpdateStatusMessage($"下载失败，{RetryIntervalMinutes}分钟后重试（{_downloadRetryCount}/{MaxRetryCount}）");

                await Task.Delay(TimeSpan.FromMinutes(RetryIntervalMinutes));
                if (File.Exists(DownloadFilePath))
                {
                    try { File.Delete(DownloadFilePath); }
                    catch { }
                }
                await StartDownload();
            }
            else
            {
                ChangeStatus(UpgradeStatus.DownloadFailed);
            }
        }

        private Task StartInstallation()
        {
            _installationProgress = 0;
            return Task.Run(() =>
            {
                try
                {
                    ChangeStatus(UpgradeStatus.Upgrading);
                    UpdateStatusMessage("开始安装...");

                    if (!File.Exists(DownloadFilePath))
                        throw new FileNotFoundException("升级文件不存在", DownloadFilePath);

                    StopServices();
                    RunInstaller();

                    // 安装成功处理
                    _localConfig.LastUpgradeTime = DateTime.Now;
                    _localConfig.UpgradePostpone = 0;
                    SaveLocalConfig();
                    ChangeStatus(UpgradeStatus.UpgradeSuccess);
                    UpdateStatusMessage("安装完成");
                    DeleteDownloadedFile();
                    HandleRestart();
                }
                catch (Exception ex)
                {
                    Logger.Error($"安装失败: {ex.Message}");
                    ChangeStatus(UpgradeStatus.UpgradeFailed);
                    UpdateStatusMessage($"安装失败: {ex.Message}");

                    // 安装失败强制删除文件
                    ForceDeleteOnFailure();
                }
            });
        }

        private void RunInstaller()
        {
            try
            {
                string args = Path.GetExtension(DownloadFilePath).Equals(".msi", StringComparison.OrdinalIgnoreCase)
                    ? "/quiet /norestart" : " ";  ///s /verysilent

                var psi = new ProcessStartInfo(DownloadFilePath, args)
                {
                    Verb = "runas",
                    UseShellExecute = true,
                    WindowStyle = ProcessWindowStyle.Normal
                };

                using (var p = Process.Start(psi))
                {
                    while (!p.HasExited)
                    {
                        int progress = Math.Min(_installationProgress + 1, 100);
                        InstallProgressChanged?.Invoke(progress);
                        _installationProgress = progress;
                        p.WaitForExit(1000);
                    }
                    if (p.ExitCode != 0) throw new Exception($"安装程序退出码: {p.ExitCode}");
                }
            }
            catch (Exception ex) { Logger.Error($"安装程序执行失败: {ex.Message}"); throw; }
        }

        // 安装失败强制删除文件（核心方法）
        private void ForceDeleteOnFailure()
        {
            if (string.IsNullOrEmpty(DownloadFilePath)) return;

            try
            {
                // 步骤1：终止占用进程
                TerminateAllLockingProcesses(DownloadFilePath);

                // 步骤2：尝试直接删除
                if (TryHardDelete(DownloadFilePath))
                {
                    Logger.Info("安装失败后成功删除文件");
                    return;
                }

                // 步骤3：标记为重启后删除
                if (MarkForDeleteOnReboot(DownloadFilePath))
                    Logger.Info("文件已标记为重启后删除");
                else
                    Logger.Error("无法删除文件，也无法标记重启删除");
            }
            catch (Exception ex) { Logger.Error($"强制删除失败: {ex.Message}"); }
        }

        private void TerminateAllLockingProcesses(string filePath)
        {
            string fileName = Path.GetFileName(filePath);
            foreach (var p in Process.GetProcesses().ToList())
            {
                try
                {
                    foreach (ProcessModule m in p.Modules)
                    {
                        bool isMatch = m.FileName.Equals(filePath, StringComparison.OrdinalIgnoreCase) ||
                                      m.FileName.IndexOf(fileName, StringComparison.OrdinalIgnoreCase) >= 0;

                        if (isMatch)
                        {
                            p.CloseMainWindow();
                            if (!p.WaitForExit(2000)) p.Kill();
                            System.Threading.Thread.Sleep(500);
                        }
                    }
                }
                catch { }
            }
        }

        private bool TryHardDelete(string filePath)
        {
            if (!File.Exists(filePath)) return true;

            // 方法1：普通删除
            try { File.SetAttributes(filePath, FileAttributes.Normal); File.Delete(filePath); if (!File.Exists(filePath)) return true; }
            catch { }

            // 方法2：命令行删除
            try
            {
                Process.Start(new ProcessStartInfo("cmd.exe", $"/c del /f /q \"{filePath}\"")
                { Verb = "runas", CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden })?.WaitForExit(3000);
                if (!File.Exists(filePath)) return true;
            }
            catch { }

            // 方法3：移动后删除
            try
            {
                string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.GetExtension(filePath));
                File.Move(filePath, tempPath);
                File.Delete(tempPath);
                if (!File.Exists(filePath)) return true;
            }
            catch { }

            return false;
        }

        private bool MarkForDeleteOnReboot(string filePath)
        {
            try { return MoveFileEx(filePath, null, MOVEFILE_DELAY_UNTIL_REBOOT); }
            catch { return false; }
        }

        private void DeleteDownloadedFile()
        {
            if (string.IsNullOrEmpty(DownloadFilePath) || !File.Exists(DownloadFilePath)) return;
            try { File.Delete(DownloadFilePath); }
            catch (Exception ex) { Logger.Warn($"删除文件失败: {ex.Message}"); }
        }

        private void HandleRestart()
        {
            if (_serverConfig.ForceSystemRestart)
            {
                UpdateStatusMessage("30秒后重启系统...");
                if (!CompatibilityHelper.RestartSystem(30))
                    UpdateStatusMessage("无法自动重启，请手动重启");
            }
            else
            {
                UpdateStatusMessage("重启服务完成");
                StartServices();
            }
        }

        public void PostponeUpgrade()
        {
            _localConfig.UpgradePostpone++;
            if (_localConfig.UpgradePostpone >= 5 && _serverConfig != null)
                _serverConfig.ForceUpgrade = true;

            SaveLocalConfig();
            ChangeStatus(UpgradeStatus.UpgradeDelay);
            UpdateStatusMessage("升级已推迟");
        }

        private void StopServices() {
            /* 实现服务停止逻辑 */
            Logger.Info("停止相关服务...");

            // stop debugView

            // stop vdagent

            // stop pv-enc

            Logger.Info("服务已停止...");
        }

        private void StartServices() {
            /* 实现服务启动逻辑 */
            Logger.Info("启动相关服务...");

            // start vdagent

            // start debugView


            Logger.Info("服务启动完成...");
        }

        private void ChangeStatus(UpgradeStatus status)
        {
            CurrentStatus = status;
            StatusChanged?.Invoke(status);
        }

        private void UpdateStatusMessage(string message)
        {
            StatusMessageUpdated?.Invoke(message);
        }

        public ServerUpgradeConfig GetServerConfig() => _serverConfig;
    }
}
